/**
 * jims
 */
package com.jims.master.modules.finance.service;

import com.jims.master.common.mapper.JsonMapper;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.NumberUtils;
import com.jims.master.common.utils.PrintPdfUtils;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.doctor.dao.ClinicMasterDao;
import com.jims.master.modules.doctor.dao.ClinicOrdersDao;
import com.jims.master.modules.doctor.entity.ClinicMaster;
import com.jims.master.modules.doctor.entity.PatMasterIndex;
import com.jims.master.modules.finance.dao.OutpBillItemsDao;
import com.jims.master.modules.finance.dao.OutpRcptMasterDao;
import com.jims.master.modules.finance.entity.OutpBillItems;
import com.jims.master.modules.finance.entity.OutpRcptMaster;
import com.jims.master.modules.med.dao.MedicalCardMasterDao;
import com.jims.master.modules.med.entity.MedicalCardConsumeDetail;
import com.jims.master.modules.med.entity.MedicalCardConsumeMaster;
import com.jims.master.modules.med.entity.MedicalCardMaster;
import com.jims.master.modules.med.service.MedicalCardConsumeDetailService;
import com.jims.master.modules.med.service.MedicalCardConsumeMasterService;
import com.jims.master.modules.sys.dao.CompanyDao;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.utils.DictUtils;
import com.jims.master.modules.sys.utils.UserUtils;
import com.jims.master.modules.utils.NumberToCN;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 门诊收费记录Service
 * @author chentao
 * @version 2017-03-06
 */
@Service
@Transactional(readOnly = true)
public class OutpRcptMasterService extends CrudService<OutpRcptMasterDao, OutpRcptMaster> {
	@Autowired
	private ClinicOrdersDao clinicOrdersDao;
	@Autowired
	private OutpBillItemsDao outpBillItemsDao;
    @Autowired
    private MedicalCardMasterDao medicalCardMasterDao;
    @Autowired
    private MedicalCardConsumeMasterService medicalCardConsumeMasterService;
    @Autowired
    private MedicalCardConsumeDetailService medicalCardConsumeDetailService;
	@Autowired
	private CompanyDao companyDao;
	@Autowired
	private ClinicMasterDao clinicMasterDao;
	public OutpRcptMaster get(String id) {
		return super.get(id);
	}
	
	public List<OutpRcptMaster> findList(OutpRcptMaster outpRcptMaster) {
		return super.findList(outpRcptMaster);
	}
	
	public Page<OutpRcptMaster> findPage(Page<OutpRcptMaster> page, OutpRcptMaster outpRcptMaster) {
		return super.findPage(page, outpRcptMaster);
	}

	/**
	 * 门诊退费查询
	 * @param page
	 * @param outpRcptMaster
	 * @return
	 * @author 赵宁
	 */
   public Page<OutpRcptMaster> findRefundCharges(Page<OutpRcptMaster> page, OutpRcptMaster outpRcptMaster){
	   outpRcptMaster.updateOrgId();
	   outpRcptMaster.setPage(page);
	   page.setList(dao.findRefundCharges(outpRcptMaster));
	   return page;
   }
	/**
	 * 收费时计算优惠价格
	 * @param clinicNo
	 * @param chargeType
	 * @return String
	 * @author 赵宁
	 */
	@Transactional(readOnly = false)
    public String preferentialCosts(String chargeType,String clinicNo){
			Map<String,Object> map=new HashMap<String, Object>();
		    map.put("chargeType",chargeType);
		    map.put("clinicNo",clinicNo);
		    map.put("orgId",UserUtils.getOrgId());
			map.put("ret", "1123456");
           dao.getPrefer(map);
		 return (String)map.get("ret");
	}
	/**
	 * 门诊收费数据保存
	 * @param costs
	 * @param orderIds
	 * @param payType
	 * @param payMoney
     * @param cardNo 卡号
     * @param cardPayFlag 使用标志
	 * @return String
	 * @author 赵宁
	 */
	@Transactional(readOnly = false)
	public Map<String ,Object> save(String costs,String orderIds,String payType,String payMoney,
									String totalMoney,String cardNo,String cardPayFlag,String serialNo) {
		User user =UserUtils.getUser();
		String [] types=payType.split(",");
		String [] moneys=payMoney.split(",");
		String [] orderData = orderIds.split(",");
		String ordersJsonData = "[";
        // 执行科室分组收费  deptId ordersId price
        List<BaseDto> baseDtos = clinicOrdersDao.filterOrders(orderData);
        if(baseDtos.size()>0){
            for(int a=0;a<baseDtos.size();a++){
                String orders= (String)baseDtos.get(a).get("order_id");
                String price =(String) baseDtos.get(a).get("price").toString();
                String orderJson = "[";
                String [] ordersArry =orders.split(",");
                if(ordersArry.length>0){
                    for(int o=0;o<ordersArry.length;o++){
                        orderJson +="{\"orderId\":\"" + ordersArry[o] + "\"},";
                    }
                }
                orderJson =orderJson.substring(0,orderJson.length()-1)+"],";
                orderJson+="\"price\":\""+price+"\"";
                ordersJsonData+="{\"orders\":"+orderJson+"},";
            }
        }
        ordersJsonData=ordersJsonData.substring(0,ordersJsonData.length()-1)+"]";

        Double changes=Double.parseDouble(totalMoney)-Double.parseDouble(costs);
        //拼接支付类型和金额
        String typeJson="[";
        for(int j=0;j<types.length;j++){
            String type=types[j];
            String money = moneys[j];
            if(type.equals("1")){
                money=Double.parseDouble(money)-changes+"";
            }
            typeJson+= "{\"payType\":\""+types[j]+"\",\"money\":\""+money+"\"},";
        }
        typeJson = typeJson.substring(0,typeJson.length()-1)+"]";
        //拼接整体
		String jsonInfo="{";
		jsonInfo+="\"serialNo\":\""+serialNo+"\",";//流水号
		jsonInfo+="\"costs\":\""+costs+"\",";//费用
		jsonInfo+="\"orderIds\":"+ordersJsonData+",";//orderIds
		jsonInfo+="\"type\":"+typeJson+"";//支付类型
		jsonInfo+="}";
       //登录人信息
		String loginInfoJson = JsonMapper.toJsonString(user);
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("jsonInfo",jsonInfo);
		map.put("loginInfo",loginInfoJson);
		map.put("ret", "1123456");
		dao.saveCharges(map);
        String returnVal=(String)map.get("ret") ;
        String rcptNo = (String)map.get("serialNo");
        Map<String ,Object> resultMap= new HashMap<>();
        resultMap.put("result",returnVal);
        resultMap.put("serialNo",rcptNo);
        if(isOneCard(returnVal,cardPayFlag,cardNo)) {
			int value = medicalCardConsumeMasterService.outpSave(baseDtos, cardNo, costs);
			if (value > 0) {
				return resultMap;
			} else {
				return resultMap;
			}
		}
        return resultMap;
	}



    /**
     * 是否为一卡通收费
     * @param proVal
     * @param cardPayFlag
     * @param cardNo
     * @return
     */
    private boolean isOneCard(String proVal,String cardPayFlag,String cardNo){
        boolean returnVal=false;
        if("0".equals(proVal)&&"1".equals(cardPayFlag)&&cardNo!=null){
            returnVal=true;
        }
        return returnVal;
    }
	@Transactional(readOnly = false)
	public int delete(OutpRcptMaster outpRcptMaster) {
		return super.delete(outpRcptMaster);
	}

	/**
	 * 根据门诊号查询，门诊退费信息
	 * @param clinicNo
	 * @param orgId
	 * @return list
	 * @author赵宁 
	 */
	public List<OutpRcptMaster> getRcptInfo(String clinicNo,String orgId){
		return  dao.getBillInfo(clinicNo,orgId);
	}

	/**
	 * 确认退费
	 * @param rcptNos
	 * @return String
	 * @author 赵宁
	 */
	@Transactional(readOnly = false)
	public String conRefCharges(String rcptNos,String totalCosts,String clinicNo,
								String serialNos,String cardNo, String moneyTypes,String payTypes,String payMoneys){
		String newRcptNo= NumberUtils.getRcptNo();
		String [] rcptNoArr=rcptNos.split(",");
		String [] costsArr=totalCosts.split(",");
		String [] serialNoArr=serialNos.split(",");
		String [] payTypeArry = payTypes.split(",");
		String [] payMoneyArry = payMoneys.split(",");
		String rcptJson="[";
		for(int j=0;j<rcptNoArr.length;j++){
			rcptJson+="{\"rcptNo\":\"" + rcptNoArr[j] + "\",";
            rcptJson+="\"serialNo\":\"" +serialNoArr[j] + "\",";
			rcptJson+="\"aa\":\""+costsArr[j]+"\"},";
		}
		rcptJson = rcptJson.substring(0, rcptJson.length() -1)+"]";
		//拼接支付类型和金额
		String typeJson="[";
		for(int h=0;h<payTypeArry.length;h++){
			String type=payTypeArry[h];
			String money = payMoneyArry[h];
			typeJson+= "{\"payType\":\""+type+"\",\"money\":\""+money+"\"},";
		}
		typeJson = typeJson.substring(0,typeJson.length()-1)+"]";
		String jsonInfo="{";
		jsonInfo+="\"newRcptNo\":\""+newRcptNo+"\",";
		jsonInfo+="\"type\":"+typeJson+",";//支付类型
		jsonInfo+="\"rcptNos\":"+rcptJson;
		jsonInfo+="}";
		String loginInfoJson = JsonMapper.toJsonString(UserUtils.getUser());
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("jsonInfo",jsonInfo);
		map.put("loginInfo",loginInfoJson);
		map.put("ret", "1123456");
		dao.confirmRefund(map);
        if(StringUtils.isNotBlank(cardNo)){
            MedicalCardMaster medicalCardMaster=medicalCardMasterDao.findByCardNo(new MedicalCardMaster(cardNo));
            medicalCardMaster.setBalance(medicalCardMaster.getBalance()+this.getReturnNum(totalCosts));
            int i=medicalCardMasterDao.updateBalance(medicalCardMaster);
            if(i>0){
                List<String> rcptLists=Arrays.asList(rcptNoArr);
                List<MedicalCardConsumeMaster> masters=medicalCardConsumeMasterService.findByRcpts(rcptLists);
                for(MedicalCardConsumeMaster master:masters){
                    master.setLoss(master.getConsumeMoney());
                    i=medicalCardConsumeMasterService.save(master);
                    if(i>0){
                        for(MedicalCardConsumeDetail detail:master.getMedicalCardConsumeDetailList()){
                            detail.setData(master.getId(),detail.getConsumeMoney());
                            medicalCardConsumeDetailService.save(detail);
                        }
                    }
                }
            }else{
                throw new IllegalArgumentException("一卡通余额增加失败");
            }
        }
		return (String)map.get("ret") ;

	}

    /**
     * 获取退费总金额
     * @param totalCosts
     * @return
     */
    private double getReturnNum(String totalCosts) {
        double returnVal=0.0;
        String[] totalCostsArr=totalCosts.split(",");
        for(String singleCosts:totalCostsArr){
            returnVal+=Double.parseDouble(singleCosts);
        }
        return returnVal;
    }

    /**
	 * 修改收费状态
	 * @param rcptNo
	 * @return
	 */
	@Transactional(readOnly = false)
	public int updateChargeFlag(String rcptNo,String chargeIndicator,String orgId){
		int num = dao.updateChargeFlag(rcptNo,chargeIndicator,orgId);
		return num;
	}

	/**
	 * 门诊收费打印
	 * @param outpRcptMaster
	 * @return String
	 * @author 赵宁
	 */
	public String printCharges(OutpRcptMaster  outpRcptMaster){
		User user = UserUtils.getUser();
		String printPath = "";
		String hospital = user.getCompany().getName();
        List<OutpRcptMaster> outpRcptMasters =  dao.findList(outpRcptMaster);
		PatMasterIndex patMasterIndex = new PatMasterIndex();
		ClinicMaster clinicMaster= new ClinicMaster();
		Double totalCosts = 0.0;
		Double totalCharges =0.0;
        for(int i=0;i<outpRcptMasters.size();i++){
			OutpRcptMaster master = outpRcptMasters.get(i);
			String clinicId = clinicOrdersDao.getOrdersByRcpt(master.getRcptNo()).getClinicId();
			clinicMaster = clinicMasterDao.get(clinicId);
            totalCosts += Double.parseDouble(master.getTotalCosts()) ;
			totalCharges +=Double.parseDouble(master.getTotalCharges());
		}
		OutpBillItems outpBillItems = new OutpBillItems();
		outpBillItems.setSerialNo(outpRcptMaster.getSerialNo());
		outpBillItems.setOrgId(user.getOrgId());
		List<BaseDto> outpBillItemses = outpBillItemsDao.findListItems(outpBillItems);
		String name =clinicMaster.getName();
		String sex = DictUtils.getDictLabels(clinicMaster.getSex(), "SEX_DICT", "");
		BigDecimal numberOfMoney = new BigDecimal(totalCharges);
		String s = NumberToCN.number2CNMontrayUnit(numberOfMoney);
		String insuranceType =DictUtils.getDictLabels(clinicMaster.getChargeType(), "CHARGE_TYPE_DICT", "");
		Map map = new HashMap();
		map.put("clinicNo",clinicMaster.getClinicNo());
		map.put("itemClass","合收");
		map.put("hospital",hospital);
		map.put("name",name);
		map.put("sex",sex);
		map.put("cost",totalCharges);
		map.put("capital",s.toString());
		String deptName = "";
        if(outpBillItemses.size()>10){
			List<BaseDto> baseDtoList6=new ArrayList<BaseDto>();
			List<BaseDto> baseDtoListq=new ArrayList<BaseDto>();
			for (int i = 0; i <outpBillItemses.size(); i++) {
				if(i<10){
					baseDtoList6.add(outpBillItemses.get(i));
				}else{
					baseDtoListq.add(outpBillItemses.get(i));
				}

			}
			map.put("leftList",baseDtoList6);
			map.put("rigthList",baseDtoListq);
		}else{
			map.put("leftList",outpBillItemses);
			map.put("rigthList",null);
		}
		map.put("SUBREPORT_DIR","his/finance/outpatientCharge_subreport.jasper");
		map.put("receivables", user.getName());//操作员
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		map.put("date",sdf.format(new Date()));
		printPath = PrintPdfUtils.previewPdf(user.getId(), "his/finance/outpatientCharge.jasper", map, outpBillItemses, "outpatientCharge");
		return printPath;
	}

	public OutpRcptMaster findSerialNoRcptNo(String serialNo){
		OutpRcptMaster outpRcptMaster = new OutpRcptMaster();
		outpRcptMaster.setSerialNo(serialNo);
		outpRcptMaster.updateOrgId();
		return   dao.findSerialNoRcptNo(outpRcptMaster);
	}

	public  BaseDto getViemCode(String userId){
		return dao.getViemCode(userId);
	};
}